How to reduce overly-redundant for loops

join shbcf.ru